package com.sline.file;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;

@WebServlet("/file/download")
public class downloadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/x-msdownload");
        String filename = req.getParameter("fileName");

        String userAgent = req.getHeader("User-Agent");
        if (userAgent.contains("MSIE")) {   // IE浏览器
            resp.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "utf-8"));
        } else {                            //  其他浏览器
            resp.setHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO-8859-1"));
        }

        String path = req.getServletContext().getRealPath("/WEB-INF/download");

        File file = new File(path, filename);
        ServletOutputStream outputStream = resp.getOutputStream();
        Files.copy(Paths.get(file.getAbsolutePath()), outputStream);
    }
}
